package com.stary.pay.unionpay.api.util;

import java.net.URL;
import java.util.Map.Entry;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;

import com.stary.pay.unionpay.api.UnionpayConstants;

/**
 * 基于apache httpclient 组件实现的网络工具类
 * @author stary {@link stary1993@qq.com}
 * @since 2019-6-20 
 */
public class WebUtils {


	/**
	 * 后台交易
	 * @param requestUrl
	 * @param data
	 * @param connectTimeoutMs
	 * @param readTimeoutMs
	 * @return
	 */
	public static String requestPost(final String requestUrl, UnionpayHashMap data, int connectTimeoutMs, int readTimeoutMs, String charset) {
		PostMethod post = new PostMethod(requestUrl);
		HttpClient httpclient = null;
		try {
			post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + charset);
			post.addRequestHeader("Cache-control", "no-cache");
			post.addRequestHeader("Pragma", "no-cache");
			post.addRequestHeader("Connection", "keep-alive");
			post.addRequestHeader("User-Agent", UnionpayConstants.USER_AGENT);
			if (null != data && 0 != data.size()) {
				for (Entry<String, String> en : data.entrySet()) {
					post.addParameter(en.getKey(), en.getValue());
				}
			}
			URL url = new URL(requestUrl);
			//测试环境配置不验证SSL证书（如果接银联生产环境需要验证SSL证书，可以注释以下两行代码）
			if (requestUrl.contains("test")) {
				Protocol myhttps = new Protocol(
						url.getProtocol(), new UnionpaySSLSocketFactory(), -1 == url.getPort( ) ? 443 : url.getPort());
				Protocol.registerProtocol("https", myhttps);
			}
			httpclient = new HttpClient();
			httpclient.getHostConfiguration().setHost(url.getHost(), url.getPort(), url.getProtocol());
			httpclient.getParams().setSoTimeout(readTimeoutMs);
			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectTimeoutMs);
			int result = httpclient.executeMethod(post);
			UnionpayUtils.getLogger().debug("HTTP return status-code:[" + result + "]");
			if (result == HttpStatus.SC_OK) {
				// 读取内容
				byte[] responseBody = post.getResponseBody();
				String resp = new String(responseBody, charset);
				UnionpayUtils.getLogger().debug("return a message:[" + resp + "]");
				return resp;
			}
		} catch (Exception e) {
			UnionpayUtils.getLogger().error(requestUrl + " post error", e);
		} finally {
			post.releaseConnection();
			if (httpclient != null) {
				((SimpleHttpConnectionManager) httpclient.getHttpConnectionManager()).shutdown();
			}
		}
		return null;
	}

	/**
	 * http Get方法 便民缴费产品中使用
	 * @param requestUrl
	 * @param data
	 * @param connectTimeoutMs
	 * @param readTimeoutMs
	 * @return
	 */
	public static String requestGet(final String requestUrl, UnionpayHashMap data, int connectTimeoutMs, int readTimeoutMs, String charset) {
		GetMethod get = new GetMethod(requestUrl);
		HttpClient httpclient = null;
		try {
			get.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + charset);
			get.addRequestHeader("Cache-control", "no-cache");
			get.addRequestHeader("Pragma", "no-cache");
			get.addRequestHeader("Connection", "keep-alive");
			get.addRequestHeader("User-Agent", UnionpayConstants.USER_AGENT);
			URL url = new URL(requestUrl);
			//测试环境配置不验证SSL证书（如果接银联生产环境需要验证SSL证书，可以注释以下两行代码）
			if (requestUrl.contains("test")) {
				Protocol myhttps = new Protocol(url.getProtocol(), new UnionpaySSLSocketFactory(), -1 == url.getPort() ? 443 : url.getPort());
				Protocol.registerProtocol("https", myhttps);			
			}
			httpclient = new HttpClient();
			httpclient.getHostConfiguration().setHost(url.getHost(), url.getPort(), url.getProtocol());
			httpclient.getParams().setSoTimeout(readTimeoutMs);
			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectTimeoutMs);
			int result = httpclient.executeMethod(get);
			UnionpayUtils.getLogger().debug("HTTP return status-code:[" + result + "]");
			if (result == HttpStatus.SC_OK) {
				// 读取内容
				byte[] responseBody = get.getResponseBody();
				String resp = new String(responseBody, charset);
				UnionpayUtils.getLogger().debug("return a message:[" + resp + "]");
				return resp;
			}
		} catch (Exception e) {
			UnionpayUtils.getLogger().error(requestUrl + " get error", e);
		} finally {
			get.releaseConnection();
			if (httpclient != null) {
				((SimpleHttpConnectionManager) httpclient.getHttpConnectionManager()).shutdown();
			}
		}
		return null;
	}

}
